#include "../logs/log.hpp"
#include <unistd.h>
enum class  TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};
class RollByTimeSink : public mylog::LogSink
{
private:
    std::string _basename;
    std::ofstream _ofs;
    size_t _cur_gap;
    size_t  _gap_size;
    size_t _name_count;
private:
    std::string createNewFile()
    {
        std::stringstream ss;
        ss << _basename;
        time_t ctime = mylog::util::Date::getTime();
        struct tm lt;
        localtime_r(&ctime, &lt);
        
        ss << lt.tm_year + 1900;
        ss << lt.tm_mon + 1;
        ss << lt.tm_mday;
        ss << lt.tm_hour;
        ss << lt.tm_min;
        ss << lt.tm_sec;
        //ss << "-";
        //ss << _name_count++;
        ss << ".log";
        return  ss.str();
    }
public:
    RollByTimeSink(const std::string& basename, TimeGap gap_type):_basename(basename)
    {
        switch(gap_type)
        {
            case TimeGap::GAP_SECOND : _gap_size = 1; break;
            case TimeGap::GAP_MINUTE : _gap_size = 60; break;
            case TimeGap::GAP_HOUR : _gap_size = 3600; break;
            case TimeGap::GAP_DAY : _gap_size = 3600*24; break;
        }
        _cur_gap = _gap_size == 1 ? mylog::util::Date::getTime() : mylog::util::Date::getTime() % _gap_size;
        _name_count = 0;
        std::string pathname = createNewFile();
        // 1.创建日志所在的目录
        mylog::util::File::createDirectory(mylog::util::File::path(pathname));
        // 2.创建并打开日志文件
        _ofs.open(pathname, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }
    void log(const char *data, size_t len) override
    {
        time_t cur = mylog::util::Date::getTime();
       if((cur % _gap_size) != _cur_gap)
       {
            _ofs.close();
            std::string pathname = createNewFile();
            _ofs.open(pathname, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
       }
       _ofs.write(data, len);
       assert(_ofs.good());
    }
};

int main()
{
    std::unique_ptr<mylog::LoggerBuilder> loggerbuild(new mylog::LocalLoggerBuilder());
    loggerbuild->buildLoggerName("sync_logger");
    loggerbuild->buildLimitLevel(mylog::LogLevel::value::WARN);
    loggerbuild->buildLoggerType(mylog::LoggerType::LOGGER_SYNC);
    loggerbuild->buildformater("[%d{%H:%M:%S}][%p]%T%m%n");
    loggerbuild->buildSinks<mylog::StdoutSink>();
    loggerbuild->buildSinks<RollByTimeSink>("./logfile/rool-async-by-time", TimeGap::GAP_SECOND);
    mylog::Logger::ptr logger = loggerbuild->build();

    time_t old = mylog::util::Date::getTime();
    while(mylog::util::Date::getTime() < old + 5)
    {
        logger->fatal("%s", "日志测试");
        usleep(1000);
    }
    return 0;
}